/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginDialog.java
 *
 * Created on 21-May-2009, 15:34:06
 */
package TimeRecording.forms;

import TimeRecording.business.DaisyChainSystem;
import TimeRecording.business.PasswordEncryption;
import TimeRecording.tables.Employee;
import java.awt.Color;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.jdesktop.application.Action;

/**
 *
 * @author cbegg
 */
public class LoginDialog extends javax.swing.JDialog {

    private final static int LIVE_COMBO_INDEX = 0;
    private final static int TRAINING_COMBO_INDEX = 1;

    private EntityManager liveEntityManager;
    private EntityManager trainingEntityManager;

    private static final long serialVersionUID = 1L;

    // <editor-fold defaultstate="collapsed" desc="loggedInEmployee + Getter & Setter">
    private Employee loggedInEmployee;

    public Employee getLoggedInEmployee() {
        return loggedInEmployee;
    }

    public void setLoggedInEmployee(Employee loggedInEmployee) {
        Employee oldLoggedInEmployee = this.loggedInEmployee;
        this.loggedInEmployee = loggedInEmployee;
        firePropertyChange("loggedInEmployee", oldLoggedInEmployee, loggedInEmployee);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="loginValid + Getter & Setter">
    protected boolean loginValid;

    public boolean isLoginValid() {
        return loginValid;
    }

    public void setLoginValid(boolean loginValid) {
        boolean oldLoginValid = this.loginValid;
        this.loginValid = loginValid;
        firePropertyChange("loginValid", oldLoginValid, loginValid);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="entityManager + Getter & Setter">
    private EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        EntityManager oldEntityManager = this.entityManager;
        this.entityManager = entityManager;
        firePropertyChange("entityManager", oldEntityManager, entityManager);
    } // </editor-fold>

    /** Creates new form LoginDialog */
    @SuppressWarnings("unchecked")
    public LoginDialog(java.awt.Frame parent, boolean modal) {

        super(parent, modal);
        initComponents();
        getRootPane().setDefaultButton(loginButton);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        usernameText = new javax.swing.JTextField();
        passwordField = new javax.swing.JPasswordField();
        usernameLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        loginButton = new javax.swing.JButton();
        databaseLabel = new javax.swing.JLabel();
        databaseCombo = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getResourceMap(LoginDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setIconImage(null);
        setName("Form"); // NOI18N
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        usernameText.setText(resourceMap.getString("usernameText.text")); // NOI18N
        usernameText.setName("usernameText"); // NOI18N
        usernameText.setPreferredSize(new java.awt.Dimension(200, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 100;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(10, 4, 5, 10);
        getContentPane().add(usernameText, gridBagConstraints);

        passwordField.setText(resourceMap.getString("passwordField.text")); // NOI18N
        passwordField.setName("passwordField"); // NOI18N
        passwordField.setPreferredSize(new java.awt.Dimension(200, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 100;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 4, 5, 10);
        getContentPane().add(passwordField, gridBagConstraints);

        usernameLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        usernameLabel.setLabelFor(usernameText);
        usernameLabel.setText(resourceMap.getString("usernameLabel.text")); // NOI18N
        usernameLabel.setName("usernameLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 4);
        getContentPane().add(usernameLabel, gridBagConstraints);

        passwordLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        passwordLabel.setLabelFor(passwordField);
        passwordLabel.setText(resourceMap.getString("passwordLabel.text")); // NOI18N
        passwordLabel.setName("passwordLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 4);
        getContentPane().add(passwordLabel, gridBagConstraints);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getActionMap(LoginDialog.class, this);
        loginButton.setAction(actionMap.get("login")); // NOI18N
        loginButton.setText(resourceMap.getString("loginButton.text")); // NOI18N
        loginButton.setName("loginButton"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 10, 0);
        getContentPane().add(loginButton, gridBagConstraints);

        databaseLabel.setText(resourceMap.getString("databaseLabel.text")); // NOI18N
        databaseLabel.setName("databaseLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 4);
        getContentPane().add(databaseLabel, gridBagConstraints);

        databaseCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Live Database", "Training Database" }));
        databaseCombo.setName("databaseCombo"); // NOI18N
        databaseCombo.setPreferredSize(new java.awt.Dimension(200, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 4, 5, 10);
        getContentPane().add(databaseCombo, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    @Action
    @SuppressWarnings("unchecked")
    public void login() {

        // Choose between the live and the training database
        
        if (databaseCombo.getSelectedIndex() == LIVE_COMBO_INDEX) {
            if (liveEntityManager == null) {
                liveEntityManager = Persistence.createEntityManagerFactory(
                        DaisyChainSystem.LIVE_PERSISTENCE_UNIT).createEntityManager();
            }
            entityManager = liveEntityManager;

        } else if (databaseCombo.getSelectedIndex() == TRAINING_COMBO_INDEX) {
            if (trainingEntityManager == null) {
                trainingEntityManager = Persistence.createEntityManagerFactory(
                        DaisyChainSystem.TRAINING_PERSISTENCE_UNIT).createEntityManager();
            }
            entityManager = trainingEntityManager;
            
        } else {
            return;
        }

        // Assume that the login has failed until we know otherwise
        loginValid = false;

        // Attempot to find the username in the chosen database
        List<Employee> employeeList = Employee.getEmployeesByUsername(
                entityManager, usernameText.getText());
        
        if (!employeeList.isEmpty()) {

            loggedInEmployee = employeeList.get(0);
            
            String suppliedPassword = new String(passwordField.getPassword());
            String recordedPassword = loggedInEmployee.getPassword();

            // No password stored for this user?
            if (recordedPassword == null || recordedPassword.length() == 0) {
                loginValid = (suppliedPassword.length() == 0);

            } else {
                // Encrypt the supplied password and compare it against
                // the recorded (and pre-encrypted) recorded password

                String encryptedPassword = PasswordEncryption.Password(suppliedPassword);
                loginValid = encryptedPassword.equals(recordedPassword);
            }
        }
        
        if (loginValid) {
            if (entityManager == trainingEntityManager) {
                UIManager.put("Button.foreground", Color.BLUE);
                UIManager.put("ToggleButton.foreground", Color.BLUE);
                UIManager.put("TextField.foreground", Color.BLUE);
                UIManager.put("FormattedTextField.foreground", Color.BLUE);
            }
            setVisible(false);
        } else {
            JOptionPane.showMessageDialog(this,
                    "Invalid username/password",
                    "Input Error",
                    JOptionPane.ERROR_MESSAGE);
            passwordField.requestFocus();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox databaseCombo;
    private javax.swing.JLabel databaseLabel;
    private javax.swing.JButton loginButton;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JLabel usernameLabel;
    private javax.swing.JTextField usernameText;
    // End of variables declaration//GEN-END:variables
}